import Return2Icon from "@src/assets/return2.svg?react"
import {useLocation, useNavigate} from "react-router-dom";
import "./index.scss"
import InputIcon from "@src/components/inputIcon";
import {useEffect, useState} from "react";
import NextIcon from "@src/assets/next.svg?react"
import PreviousIcon from "@src/assets/previous.svg?react"
import ChattingRecords from "@src/pages/home/chatRoom/chatRoomDetailed/_components/chattingRecords";
import {socketCreate} from "@src/store/socket"
import {chatRoomListDataType, Member, states} from "../default/index"
import {useRequest} from "ahooks";
import {CurrentSong, getChatroomSongs} from "@src/services/chatRoom.ts";
import SongsList from "./_components/songsList"
import {useAudioPlayer} from "@src/store/music";
import UserMemorialTablet from "@src/pages/home/chatRoom/chatRoomDetailed/_components/userMemorialTablet";
import {songUrl} from "@src/services/music"
import {ThemeContext} from "./_context/index.ts"
import toast from 'react-hot-toast';
import Lyric from "@src/components/lyric";
import {messageAudioCreate} from "@src/store/messageAudio.ts";

//用户
interface Sender {
    avatar: string;
    name: string;
    email: string | null;
    isVisitor: boolean;
}

//消息
interface Message {
    id: string;
    groupId: string;
    content: string;
    sender: Sender;
    timestamp: string;
}

export interface newUserType extends Member {
    newContent: string | null;
    contentIsShow: boolean;
}


/**
 * @param timeStr 字符串时间
 * @param seconds 秒数
 * @return {boolean} boolean 判断时间是否超过当前时间
 * */
function isWithinSeconds(timeStr: string, seconds: number): boolean {
    // 将传入的时间字符串转换为 Date 对象
    const targetTime = new Date(timeStr);
    // 获取当前时间
    const currentTime = new Date();

    // 计算两个时间的差值（单位：毫秒）
    const timeDiff = currentTime.getTime() - targetTime.getTime();

    // 将差值转换为秒
    const timeDiffInSeconds = Math.floor(timeDiff / 1000);

    // 判断是否在指定秒数范围内
    return timeDiffInSeconds <= seconds;
}

const ChatRoomDetailed = () => {
    const {pause, setSongUrlData, play, setSong, percentage, setProgress, isPlaying, song} = useAudioPlayer()
    const {chatRoomAudio} = messageAudioCreate()
    const navigate = useNavigate();
    //房间 信息
    const [locationState, setLocationState] = useState<chatRoomListDataType>(useLocation().state);
    //获取歌曲列表
    const getChatroomSongsApi = useRequest(getChatroomSongs, {manual: true})
    const [getChatroomSongsApiData, setGetChatroomSongsApiData] = useState<CurrentSong[]>([])
    const songUrlApi = useRequest(songUrl, {manual: true});
    //歌曲列表显示隐藏
    const [SongsListIsOpen, setSongsListIsOpen] = useState(false)
    //聊天记录 显示
    const [open, setOpen] = useState(false);
    //输入框内容
    const [inputValue, setInputValue] = useState("");
    const {socket} = socketCreate();
    //默认用户 类型
    const [user, setUser] = useState<Member[]>([])
    //消息列表
    const [recordList, setRecordList] = useState<Message[]>([])
    //新用户类型
    const [newUser, setNewUser] = useState<newUserType[]>([])
    //消息持续时间 单位秒
    const MessageDuration = 10
    //发信息
    const sendClick = () => {
        if (inputValue.trim() !== "") {
            //发送房间 消息
            socket.emit('group:message', {
                groupId: locationState?.roomID.toString(), content: inputValue
            });
            setInputValue("")
        }
    }
    //获取播放链接
    const getSongUrlApi = (states: states) => {
        songUrlApi.runAsync(states.song.id).then((songData) => {
            setSongUrlData(songData)
            setSong({
                id: states.song.id,
                name: states.song.name,
                al: {picUrl: states.song.picUrl, id: states.song.id},
                ar: [{name: states.song.author, id: states.song.id}],
                dt: states.song.time
            });
            setTimeout(() => {
                setProgress(states.progress)
                if (states.isPlaying) {
                    play()
                }
            }, 500)
        })
    }
    //更新状态
    const update_playback_state = (states: states) => {
        socket.emit('group:update_playback_state', {
            groupId: locationState.roomID.toString(),
            state: {
                isPlaying: states.isPlaying,
                progress: percentage(),
                song: states.song,
            }
        });
    }


    // 通用的歌曲切换逻辑
    const switchSongLogic = (newSongId: number, songs?: CurrentSong[]) => {
        setProgress(0); // 重置播放进度
        setTimeout(() => {
            if (songs == undefined) {
                if (getChatroomSongsApi.data) {
                    songs = getChatroomSongsApiData;
                } else {
                    songs = []
                }
            }
            const newSong = songs.find((song) => song.id.toString() === newSongId.toString()); // 查找目标歌曲
            if (newSong) {
                setLocationState((item) => {
                    const locationState: chatRoomListDataType = JSON.parse(JSON.stringify(item));
                    if (locationState.states) {
                        locationState.states.progress = 0; // 重置播放进度
                        locationState.states.isPlaying = true; // 设置为播放状态
                        locationState.states.song = newSong; // 更新当前歌曲为目标歌曲
                        getSongUrlApi(locationState.states); // 获取目标歌曲的播放地址
                        update_playback_state(locationState.states); // 更新播放状态
                    }
                    return locationState;
                });
            } else {
                console.warn("未找到目标歌曲ID对应的歌曲");
            }

        }, 100);
    };

    // 切换歌曲的通用函数
    const switchSong = (offset: number) => {
        if (getChatroomSongsApi.data) {
            const songs = getChatroomSongsApiData;
            const currentIndex = songs.findIndex((item) => item.id === locationState.states?.song.id);
            const newIndex = (currentIndex + offset + songs.length) % songs.length; // 处理循环播放逻辑
            const newSongId = songs[newIndex].id;
            switchSongLogic(newSongId); // 调用通用逻辑
        }
    };


    //播放按钮
    const playBtn = () => {
        setLocationState((locationState) => {
            const newItem: chatRoomListDataType = JSON.parse(JSON.stringify(locationState))
            if (newItem.states) {
                newItem.states.isPlaying = !newItem.states.isPlaying
                newItem.states.progress = percentage()
                update_playback_state(newItem.states)
            }
            return newItem;
        })
    }

    useEffect(() => {
        if (locationState.states?.isPlaying) {
            play()
        } else {
            pause()
        }
    }, [locationState.states?.isPlaying]);

    //监听是否播放结束
    useEffect(() => {
        if (!isPlaying && percentage() == 100) {
            switchSong(1)
        }
    }, [isPlaying])

    //初始化
    useEffect(() => {
        pause()
        getChatroomSongsApi.runAsync(locationState.roomID).then((data) => {
            setGetChatroomSongsApiData(data.data)
        })
        if (locationState.states?.song.id) {
            getSongUrlApi(locationState.states)
        }
    }, []);


    //监听消息
    useEffect(() => {
        //获取最新消息
        const getRecord = (name: string) => {
            const record = recordList.filter((item) => {
                return item.sender.name === name;
            })
            return record[record.length - 1];
        }
        //获取最新用户状态 消息
        const getNewUser = () => {
            return user.map((item) => {
                const record: Message | undefined = getRecord(item.name)
                let contentIsShow = false
                //判断有没有消息
                if (record) {
                    contentIsShow = isWithinSeconds(record.timestamp, MessageDuration)
                    //显示的 设置 N 秒后消失
                    if (contentIsShow) {
                        setTimeout(() => {
                            setNewUser((newUser) => {
                                const temporary: newUserType[] = JSON.parse(JSON.stringify(newUser))
                                const index = temporary.findIndex(newItem => newItem.name == item.name)
                                if (index !== -1) {
                                    temporary[index].contentIsShow = false
                                }
                                const uniqueData = new Map();
                                temporary.forEach(item => {
                                    uniqueData.set(item.name, item);
                                });
                                return Array.from(uniqueData.values())
                            })
                        }, MessageDuration * 1000)
                    }
                }
                return {...item, newContent: record?.content, contentIsShow: contentIsShow}
            });
        }
        setNewUser(getNewUser())
    }, [user, recordList]);

    useEffect(() => {
        //加入群聊
        socket.emit('group:join', {groupId: locationState?.roomID.toString()});
        //获取指定群聊成员信息
        socket.emit('group:get_members', {groupId: locationState?.roomID.toString()});
        // //获取群聊播放状态
        socket.emit('group:get_playback_state', {groupId: locationState?.roomID.toString()});
        socket.on('group:members', (data) => {
            setUser(data.members)
        });
        //成员进入
        socket.on('group:member_joined', (data) => {
            setUser((user) => {
                const newUser = [...user, data.user]
                const uniqueData = new Map();
                newUser.forEach(item => {
                    uniqueData.set(item.name, item);
                });
                return Array.from(uniqueData.values())
            })
            chatRoomAudio.play().then()
        });
        //成员离开
        socket.on('group:member_left', (data) => {
            console.log(data)
            setUser((user) => user.filter((item) => item.name !== data.user.name))
        });
        //接受消息
        socket.on('group:message', (message) => {
            setRecordList((prevState) => [...prevState, message]);
        });
        //获取群聊播放状态
        socket.on("group:playback_state", (data) => {
            setLocationState((locationState) => {
                const newState: chatRoomListDataType = JSON.parse(JSON.stringify(locationState))
                if (newState.states) {
                    newState.states.isPlaying = data.state.isPlaying
                    newState.states.progress = data.state.progress
                }
                return newState
            })
        })
        //群聊更新播放状态
        socket.on('group:playback_state_updated', (data) => {
            setLocationState((locationState) => {
                if (locationState.states) {
                    if (locationState.states.song.id !== data.state.song.id) {
                        getSongUrlApi(data.state)
                    }
                }
                return {...locationState, states: data.state}
            })
        });
        //歌曲添加通知
        socket.on("group:hint_message", (data) => {
            setGetChatroomSongsApiData((item) => {
                const newItem: CurrentSong[] = JSON.parse(JSON.stringify(item))
                if (!newItem.some((s) => s.id.toString() == data.content.currentSong.id.toString())) {
                    toast(data.sender.name + "添加了歌曲：" + data.content.currentSong.name, {icon: "😊"})
                    newItem.push(data.content.currentSong)
                } else {
                    toast(data.sender.name + "切换歌曲：" + data.content.currentSong.name, {icon: "😊"})
                }
                switchSongLogic(data.content.currentSong.id.toString(), newItem)
                return newItem
            })
        })
        return () => {
            socket.off('group:member_joined')
            socket.off('group:member_left')
            socket.off('group:members')
            socket.off('group:message')
            socket.off('group:songs')
            socket.off('group:playback_state_updated')
            socket.off('group:hint_message')
            socket.off('group:get_playback_state')
            //离开房间
            socket.emit('group:leave', {groupId: locationState?.roomID.toString()});
            pause()
        };
    }, [socket]);


    return <div className="ChatRoomDetailed">
        <div className="background" style={{backgroundImage: `url(${locationState.img})`}}></div>
        <div className="head centered">
            <Return2Icon onClick={() => navigate(-1)}></Return2Icon>
            <div>
                <h4 className="text-overflow-1">{locationState?.title}</h4>
                <p className="name">{locationState?.states?.song.name}<span>{locationState?.states?.song.author}</span>
                </p>
            </div>
            <div>{user.length}/{locationState?.maxUsersLength}</div>
        </div>

        <div className="content">
            <div className="record-player">
                <div className="pole"
                     style={{transform: locationState.states?.isPlaying ? "rotate(0deg)" : "rotate(-20deg)"}}>
                    <div></div>
                </div>
                <div className="picture centered"
                     style={{animationPlayState: locationState.states?.isPlaying ? 'running' : 'paused'}}>
                    <div className="picUrl">
                        <img src={locationState?.states?.song.picUrl} alt=""/></div>
                </div>
            </div>
            <div className="controller">
                <div onClick={() => switchSong(-1)}><PreviousIcon></PreviousIcon></div>
                <div>
                    <div onClick={playBtn}
                         className={"play-btn " + (locationState?.states?.isPlaying && "isPlay")}></div>
                </div>
                <div onClick={() => switchSong(1)}><NextIcon></NextIcon></div>
            </div>
            <div className="lyric-box">
                <Lyric id={song.id}></Lyric>
            </div>

            <UserMemorialTablet newUser={newUser}></UserMemorialTablet>
            <ChattingRecords recordList={recordList} isOpen={open} setIsOpen={setOpen}></ChattingRecords>
            <ThemeContext.Provider value={{
                currentSongList: getChatroomSongsApiData,
                switchSongLogic: switchSongLogic,
                locationState: locationState,
            }}>
                <SongsList isOpen={SongsListIsOpen} setIsOpen={setSongsListIsOpen}></SongsList>
            </ThemeContext.Provider>
        </div>

        <div className="userPageFlowBtnDiv">
            <button className="z-button" onClick={() => setSongsListIsOpen(true)}>歌单列表</button>
            <button className="z-button" onClick={() => setOpen(true)}>聊天记录</button>
        </div>

        <div style={{zIndex: open ? "100" : "2"}} className="message-input bottom centered">
            <InputIcon type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)}
                       onKeyDown={(event) => {
                           if (event.key === 'Enter') {
                               sendClick()
                           }
                       }}></InputIcon>
            <button className="z-button" onClick={sendClick}>发送</button>
        </div>
    </div>
}

export default ChatRoomDetailed